const compose = (...funs) => {
    if(funs.length === 0){
        return arg=>arg;
    }else{
        if(funs.length === 1){
            return funs[0];
        }else{
            return funs.reduce((ret, item )=>(...args)=>ret(item(...args)), arg=>arg);
        }
    }
};

const applyMiddleware = (...middle) => {
    return createStore => (...args) => {
        const store = createStore(...args);
        const storeApi = {
            ...store,
            dispatch: (...args) => store.dispatch(...args)
        }

        //const dispatch = middle(storeApi)(store.dispatch);
        const mlist = middle.map(m => {
            return m(storeApi);
        });
         
        const dispatch = compose(...mlist)(store.dispatch);

        return {...store, dispatch};
    }
};

export {applyMiddleware};